package com.markerhub.security;

import com.markerhub.entity.SysUser;
import com.markerhub.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

	@Autowired
	SysUserService sysUserService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// 从数据库查询用户信息
		SysUser sysUser = sysUserService.getByUsername(username);
		if (sysUser == null) {
			throw new UsernameNotFoundException("用户名不存在");
		}
		
		// 检查用户状态
		if (sysUser.getStatus() != 1) {
			throw new UsernameNotFoundException("用户已被禁用");
		}
		
		// 获取用户权限信息
		List<GrantedAuthority> authorities = getUserAuthority(sysUser.getId());
		
		// 返回用户认证对象
		return new AccountUser(
				sysUser.getId(),
			sysUser.getUsername(),
			sysUser.getPassword(),
			authorities
		);
	}

	/**
	 * 获取用户权限方法
	 * 从数据库动态获取用户权限，基于permission_data.sql中的权限配置
	 */
	public List<GrantedAuthority> getUserAuthority(Long userId) {
		System.out.println("获取用户ID: " + userId + " 的权限信息");
		// 调用sysUserService的getUserAuthorityInfo方法动态获取权限
		String authorityInfo = sysUserService.getUserAuthorityInfo(userId);
		// 将权限字符串转换为GrantedAuthority列表
		System.out.println("权限字符串: " + authorityInfo);
		return AuthorityUtils.commaSeparatedStringToAuthorityList(authorityInfo);
	}
}
